/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.plugin.task;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mcgrobot.entity.auth.PermissionCollection;
import com.mcgrobot.entity.auth.UserCacheBean;
import com.mcgrobot.plugin.schedule.STimetask;

public class McgRobotTask {
	
	private static Logger logger = LoggerFactory.getLogger(McgRobotTask.class);
	private final static ScheduledExecutorService MCG_POOL = createScheduledExecutor();
	public static ConcurrentHashMap<String, STimetask> sTimetaskMap = new ConcurrentHashMap<>();
	
    public final static ScheduledExecutorService getScheduledExecutor() {
        return MCG_POOL;
    }	
	
    public static synchronized void init() {
    	
    	checkWebSession();
    }
    
    /**
     * 定时检查websocket session活跃状态，非活跃状态时清除用户缓存
     */
    private static void checkWebSession() {
		MCG_POOL.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
            	try {
	            	Map<String, UserCacheBean> mapSU = PermissionCollection.getInstance().getMapSU();
	            	if(mapSU != null && mapSU.size() > 0) {
	                	Set<String> keys = mapSU.keySet();
	                	for(String key : keys) {
	                		UserCacheBean ucb = mapSU.get(key);
	                		for(String mcgWebScoketCode : ucb.getUser().getWebSocketMap().keySet()) {
	                			Session session = ucb.getUser().getWebSocketMap().get(mcgWebScoketCode);
	                    		if(!session.isOpen()) {
	                    			mapSU.remove(ucb.getSessionID());
	                    		}
	                		}
	                	}
	            	}
            	}catch (Exception e) {
            		logger.error("定时检查websocket session活跃状态出错：", e);
				}
            }
		}, 20L, 5L, TimeUnit.MINUTES);
    }
    
    private final static ScheduledExecutorService createScheduledExecutor() {

        final ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(4, new McgThreadFactory("mcg-monitor", true));

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                pool.shutdown();
            }
        }, "mcg-task-ShutdownHook"));
        return pool;

    }	
}
